package com.zk.demo.control;

import com.alibaba.fastjson.JSONObject;
import com.zk.demo.bean.Fund;
import com.zk.demo.bean.FundInfo;
import com.zk.demo.bean.User;
import com.zk.demo.mapper.FundMapper;
import com.zk.demo.mapper.UserMapper;
import com.zk.demo.req.PageReq;
import com.zk.demo.req.RestQuery;
import com.zk.demo.req.UpdateUser;
import com.zk.demo.service.FundInfoService;
import com.zk.demo.service.FundService;
import com.zk.demo.service.UserService;
import com.zk.demo.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    private FundService fundService;
    @Resource
    private FundMapper fundMapper;
    @Autowired
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private FundInfoService fundInfoService;



    @RequestMapping("/")
    public String hello() {
        return "redirect:page/login/index.html";
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public ResultResponse add(@RequestBody Fund fund, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("user");
        //查询登录人信息
        if (currentUser == null) {
            return ResultResponse.buildFailed();
        }
        fund.setCreateorId(currentUser.getId());
        fund.setCreateor(currentUser.getUsername());
        fund.setPlrate(fund.getPlrate().divide(BigDecimal.valueOf(100)));
        return fundService.add(fund);

    }


    @GetMapping("/list")
    @ResponseBody
    public ResultResponse<List<Fund>> findlist(PageReq pageReq, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("user");
        //查询登录人信息
        if (currentUser == null) {
            return ResultResponse.buildFailed();
        }


        Map<String, Integer> param = new HashMap<>();
        param.put("page", (pageReq.getPage() - 1) * pageReq.getLimit());
        param.put("limit", pageReq.getLimit());
        param.put("createorId", currentUser.getId());

        List<Fund> funds = fundService.selectAll(param);

        Integer totalCount = fundMapper.selectTotalCount(param);
        return ResultResponse.buildLayuiSuccess(funds, totalCount);
    }


    @PostMapping("/del")
    @ResponseBody
    public ResultResponse del(int id) {

        return fundService.del(id);

    }


    @PostMapping("/delAll")
    @ResponseBody
    public ResultResponse delAll(@RequestBody String[] ids) {
        for (String id : ids) {
            fundMapper.del(Integer.parseInt(id));
        }
        return ResultResponse.buildSuccess();

    }

    @PostMapping("/login")
    @ResponseBody
    public ResultResponse login(User loginUser, HttpSession session) {
        User user = userService.login(loginUser);
        if (user != null) {
            //登录成功.存入session
            session.setAttribute("user", user);
            return ResultResponse.buildSuccess();
        } else {
            return ResultResponse.buildFailed(ResultCode.FAILEDADD.getCode(), "登录失败,账号密码错误");
        }


    }


    @PostMapping("/logout")
    @ResponseBody
    public ResultResponse logout(HttpSession session, HttpServletResponse response) {

        try {
            session.invalidate();
            response.sendRedirect("/");
        } catch (IOException e) {
            e.printStackTrace();
            return ResultResponse.buildFailed();
        }
        return ResultResponse.buildSuccess();


    }


    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/registered")
    @ResponseBody
    public ResultResponse registered(@RequestBody User user) {


        return userService.createUser(user);


    }

    /**
     * 修改密码
     *
     * @return
     */
    @PostMapping("/updateUser")
    @ResponseBody
    public ResultResponse updateUser(@RequestBody UpdateUser updateUser, HttpSession session) {
        //检查原密码是否正确
        User user = (User)session.getAttribute("user");
        if(user==null||updateUser==null){
            return ResultResponse.buildFailed();
        }
        //原密码
        String password=updateUser.getPassword();
        if(StringUtils.isEmpty(password)||!password.equals(user.getPassword())){
            return ResultResponse.buildFailed(ResultCode.FAILEDADD.getCode(),"原密码错误");
        }
        user.setPassword(updateUser.getNewpassword());

        return userService.updateUser(user);
    }


    /**
     * 根据基金编号查询,基金信息
     * @param fundcode
     * @return
     */
    @PostMapping("/queryFundForCode")
    @ResponseBody
    public ResultResponse queryFundForCode(@RequestBody RestQuery requestQuery) {

        try {
            String fundcode=requestQuery.getFundcode().split("-")[1];
            String forObject = HttpUtil.get(RestUrlEnum.QUERY_FUND_BY_CODE.getUrl() + fundcode + ".js", null, 5000, 5000);
            if (forObject!=null){
                String want = StringUtil.getWant(forObject, "jsonpgz(", ");");
                RestQuery restQuery = JSONObject.parseObject(want, RestQuery.class);
                return ResultResponse.buildSuccess(restQuery);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return ResultResponse.buildFailed();
    }

    /**
     * 根据基金编号查询,基金信息
     *
     * @return
     */
    @PostMapping("/queryFundInfo")
    @ResponseBody
    public ResultResponse queryFundInfo(@RequestBody FundInfo requestQuery) {
        List<FundInfo> funds = fundInfoService.selectAll(requestQuery);
        return ResultResponse.buildSuccess(funds);

    }

}
